package com.demo.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AMapUtils {

    // 高德地图Key，请替换为你自己的key
    public static final String KEY = "3fc03b32eca0055dacc39fa1152e00a8";
    private static Pattern pattern = Pattern.compile("\"location\":\"(\\d+\\.\\d+),(\\d+\\.\\d+)\"");

    /**
     * 通过具体位置获取经纬度坐标
     * @param address 地址信息
     * @return double数组 [经度, 纬度]
     */
    public static double[] addressToGPS(String address) {
        try {
            // 构造API请求URL
            String url = String.format(
                    "https://restapi.amap.com/v3/geocode/geo?address=%s&key=%s",
                    address,
                    KEY
            );

            // 发送HTTP GET请求
            URLConnection conn = new URL(url).openConnection();
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8")
            );

            // 读取响应数据
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                response.append(line);
            }

            // 使用正则表达式解析经纬度
            Matcher matcher = pattern.matcher(response.toString());
            if (matcher.find() && matcher.groupCount() == 2) {
                return new double[] {
                        Double.parseDouble(matcher.group(1)),
                        Double.parseDouble(matcher.group(2))
                };
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 使用示例
    public static void main(String[] args) {
        String address = "广东省广州市天河区黄埔大道中199号";
        double[] coordinates = addressToGPS(address);

        if (coordinates != null) {
            System.out.printf("地址: %s%n经度: %.6f%n纬度: %.6f",
                    address, coordinates[0], coordinates[1]);
        } else {
            System.out.println("坐标获取失败");
        }
    }
}